import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LanguageViewModel extends ChangeNotifier {
  Locale? _currentLocale;
  static const String _localeKey = 'selected_locale';

  Locale? get currentLocale => _currentLocale;

  LanguageViewModel() {
    _initLocale();
  }

  // 初始化语言逻辑
  Future<void> _initLocale() async {
    // 1. 尝试从本地存储加载
    final prefs = await SharedPreferences.getInstance();
    final savedLocale = prefs.getString(_localeKey);

    if (savedLocale != null) {
      _currentLocale = Locale(savedLocale);
      notifyListeners();
      return;
    }

    // 2. 本地无存储时，使用系统语言
    final systemLocale = ui.window.locale; // 获取系统默认语言
    _currentLocale = _getSupportedLocale(systemLocale.languageCode);

    notifyListeners();
  }

  // 检查系统语言是否在支持列表中，否则返回默认语言（英语）
  Locale _getSupportedLocale(String systemLangCode) {
    // 支持的语言列表（与 MaterialApp 的 supportedLocales 对应）
    const supportedLangs = ['en', 'zh', 'ja'];

    if (supportedLangs.contains(systemLangCode)) {
      return Locale(systemLangCode);
    } else {
      return const Locale('en'); // 默认英语
    }
  }
  // 保存语言设置到本地存储
  Future<void> _saveLocale(String languageCode) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_localeKey, languageCode);
  }

  // 设置语言
  void setLocale(Locale locale) {
    _currentLocale = locale;
    _saveLocale(locale.languageCode);
    notifyListeners();
  }

  // 切换到英语
  void setEnglish() {
    setLocale(const Locale('en', ''));
  }

  // 切换到中文
  void setChinese() {
    setLocale(const Locale('zh', ''));
  }

  // 切换到日语
  void setJapanese() {
    setLocale(const Locale('ja', ''));
  }
}

// 提供全局状态
class LanguageProvider extends StatelessWidget {
  final Widget child;

  const LanguageProvider({
    super.key,
    required this.child,
  });

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (ctx) => LanguageViewModel(),
      child: child,
    );
  }
}
// 定义翻译方法的类型（参数为key，返回对应语言的文本）
typedef TranslateFunc = String Function(String key);

// 扩展上下文以方便访问
extension LanguageContextExtension on BuildContext {
  LanguageViewModel get languageViewModel => read<LanguageViewModel>();
}
